package com.gzy.xuexiziliao.utils;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Component
public class WebSocketUtil {

    public static String sendWebSocketRequest(String url, String requestJson) throws Exception {
        URI uri = new URI(url);
        ImageWebSocketClient client = new ImageWebSocketClient(uri);
        client.connect();

        // 等待连接成功（最多30秒）
        if (!client.getConnectLatch().await(30, TimeUnit.SECONDS)) {
            throw new RuntimeException("WebSocket 连接超时");
        }

        // 发送消息
        client.send(requestJson);

        // 等待响应（最多20秒）
        if (!client.getLatch().await(20, TimeUnit.SECONDS)) {
            throw new RuntimeException("WebSocket 响应超时");
        }

        String response = client.getResponse();
        client.close();
        return response;
    }

    private static class ImageWebSocketClient extends WebSocketClient {
        private final CountDownLatch connectLatch = new CountDownLatch(1);
        private final CountDownLatch latch = new CountDownLatch(1);
        private String response;

        public ImageWebSocketClient(URI serverURI) {
            super(serverURI);
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            System.out.println("WebSocket 连接已建立");
            connectLatch.countDown();
        }

        @Override
        public void onMessage(String message) {
            System.out.println("收到服务器消息: " + message);
            this.response = message;
            latch.countDown();
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            System.out.println("连接关闭: " + reason);
        }

        @Override
        public void onError(Exception ex) {
            System.err.println("WebSocket 错误: " + ex.getMessage());
            ex.printStackTrace();
            connectLatch.countDown();
            latch.countDown();
        }

        public CountDownLatch getConnectLatch() {
            return connectLatch;
        }

        public CountDownLatch getLatch() {
            return latch;
        }

        public String getResponse() {
            return response;
        }
    }
}